<? 

$starttime = microtime( TRUE );

 /******************************************** /__
|___  PHPCHURRO                                 __/
/__   v 0.47                                   ___|
 \ *********************************************/
 
// http://phpchurro.org/
// https://code.google.com/p/phpchurro/

// these should be the only few lines to change in this file
// everything else in config
require '../config.php'; 

$required = array( ROOT.'model/class_Churro.php',				// Base
				   ROOT.'model/class_DB.php', 					// Db Base
				   ROOT.'model/class_DB_MySQL.php',		        // Db Adapter
				   ROOT.'model/functions_Churro.php' );			// Cool

$optional = array( ROOT.'model/functions_Debug.php',			// Nice to have
				   ROOT.'model/functions_Handy.php' );			// Also nice to have
// ok! quit editing, fool!

foreach( $required as $file ) require $file;
unset( $required );

foreach( $optional as $file ) if( file_exists($file) ) include $file;
unset( $optional );

session_start();

// database connection, passed into churro by reference
$db = new DB();

// if the user hits churro.php or this is not otherwise set, redirect to root
// set up htaccess, jerk!
$cPath = isset( $_GET['cPath'] ) ? $_GET['cPath'] : null;
if( is_null($cPath) ){
	$churro = new Churro( $db, $starttime );
	$churro->Redirect();
}

// make tradtional $_GET variables available
$query = substr( $_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], '?') + 1 ); 
$explode = explode( '&', $query ); 
foreach( $explode as $k=>$v ){
	$sep = strpos( $v, '=' );
	$key = substr( $v, 0, $sep );
	$val = substr( $v, $sep+1 );
	$_GET[$key] = $val;
}
unset( $query );

// strip slashes from $_GET, $_POST, $_REQUEST if magic quotes is on 
if( get_magic_quotes_gpc() ){
	//trigger_error( 'you dirty rat', E_USER_ERROR );	
	strip( $_GET );
	strip( $_POST );
	$_REQUEST = array_merge( $_GET, $_POST );
}

$explode = explode( '/', $cPath );
unset( $cPath );
$args = array();

$controller = 'index'; //index.php
$class = 'index'; //index
$method = 'index'; //indexAction
$path = '';

$pos = 0;

// TODO: make sure this is right.
for( $i=0; $i<count($explode); $i++ ){	
	$arg = trim( $explode[$i] );
	
	$test = '../controller/'.$path.$arg;
	
	if( is_dir($test) and !count($args) ){
		$path = $path.$arg.'/';
	} else if( is_file($test.'.php') and ( $controller == 'index' ) ){
		$controller = $arg;
	} else if( strlen($arg) > 0 ){
		array_push( $args, $arg );
	}
}
unset( $explode );

// get the controller php
$path = 'controller/'.$path.$controller.'.php';
require( $path );

if( isset($args[0]) && class_exists($args[0]) ){
	$class = $args[0];
	array_shift($args);
} else {
	$class = $controller;
}

// set this thing up!
$class = str_replace( '.', '', $class );
$churro = new $class( $db, $starttime );

$testMethod = isset( $args[0] ) ? _churro_camelCase($args[0]).'Action' : $method.'Action';
if( isset($args[0]) and method_exists($churro, $testMethod) ){
	$method = $testMethod;
	array_shift($args);
} else {
	$method = $method.'Action';
}

//and do the logic
if( method_exists($churro, 'init') ){
	$churro->init();
}

// define if is ajax request
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH']) ){
	$churro->isAjax( TRUE );
	$churro->Layout( FALSE );
}

$c = new ReflectionMethod( $class, $method );

$min = $c->getNumberOfRequiredParameters();
$max = $c->getNumberOfParameters();

if( count($args) < $min or count($args) > $max ){
	if( $churro->isAjax() ) die( json_encode(array('success' => FALSE)) );
	else $churro->Redirect( '', 404 );
}

call_user_func_array( array($churro, $method), $args );

$scripts = "";
$css = "";

//build javascript block
foreach( $churro->scripts() as $k=>$v ){
	$scripts .= '<script src="'.HTTPROOT."js/$v.js?".VERSION."\" type=\"text/javascript\"></script>\n";	
}

//build css block
foreach( $churro->css() as $k=>$v ){
	$css .= '<link href="'.HTTPROOT.'template/'.$churro->Theme().'/css/'.$v.'.css?'.VERSION.'" rel="stylesheet" type="text/css" media="screen" />'."\n";	
}

$template = $churro->Template();
$html = $churro->Render();
	
if( $churro->Layout() ){
	// normal html view
	ob_start();
		include( $template );
		$ob = ob_get_contents();
	ob_end_clean();
	
	$ob = str_replace( "\n\n", "\n", $ob );
	$ob = str_replace( "\n\t\n", "\n", $ob );
	$ob = str_replace( "\n\t\t\n", "\n", $ob );
	echo $ob;
	
} else if( count($churro->json) ){
	// json response
	if( !isset($churro->json->success) ){
		$churro->json->success = TRUE;
	}
	if( !isset($churro->json->html) ){
		$churro->json->html = $html;
	}
	
	$json = json_encode( $churro->json );
	
	$json = str_replace( '\t', '', $json );
	$json = str_replace( '\n', ' ', $json );
	
	header( 'Content-type: application/json' );
	echo $json;
} else {
	// is an rss feed
	// TODO: this
}

// thanks